<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sa="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>表单管理</title>
    <link rel="stylesheet" th:href="@{/pear/component/pear/css/pear.css}"/>
</head>
<body class="pear-container">
<div class="layui-card">
    <div class="layui-card-body">
        <form class="layui-form" action="">
            <div class="layui-form-item">
                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">表单名称</label>
                    <div class="layui-input-inline">
                        <input type="text" name="formName" placeholder="请输入表单名称" class="layui-input" id="title">
                    </div>
                </div>

                <div class="layui-form-item layui-inline">
                    <button class="layui-btn layui-btn-md" lay-submit sa:hasPermission="form_select"
                            lay-filter="form-query">
                        <i class="layui-icon layui-icon-search"></i>
                        查询
                    </button>
                    <button type="reset" class="layui-btn layui-btn-md" id="resetBtn">
                        <i class="layui-icon layui-icon-refresh"></i>
                        重置
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="layui-card">
    <div class="layui-card-body">
        <table id="form-table" lay-filter="form-table"></table>
    </div>
</div>

<script type="text/html" id="form-toolbar">
    <button class="layui-btn  layui-btn-md" sa:hasPermission="form_add" lay-event="add">
        <i class="layui-icon layui-icon-add-1"></i>
        新增
    </button>
</script>
<script type="text/html" id="form-enable">
    <input type="checkbox" name="status" value="{{d.formId}}" lay-skin="switch" lay-text="启用|禁用"
           lay-filter="form-enable" {{ d.status== 0 ? 'checked' : '' }} />
</script>
<script type="text/html" id="form-bar">
    <button class="layui-btn layui-bg-blue layui-btn-sm" sa:hasPermission="form_share" lay-event="share"><i
            class="layui-icon layui-icon-share"></i>
    </button>
    <button class="layui-btn layui-bg-blue layui-btn-sm" sa:hasPermission="form_background" lay-event="survey"><i
            class="layui-icon layui-icon-survey"></i>
    </button>
    <button class="layui-btn layui-bg-blue layui-btn-sm" sa:hasPermission="form_data" lay-event="view"><i
            class="layui-icon layui-icon-eye"></i>
    </button>
    <button class="layui-btn  layui-btn-sm" sa:hasPermission="form_update" lay-event="edit"><i
            class="layui-icon layui-icon-edit"></i>
    </button>
    <button class="layui-btn layui-btn-danger layui-btn-sm" sa:hasPermission="form_delete" lay-event="remove"><i
            class="layui-icon layui-icon-delete"></i>
    </button>
</script>


<script th:src="@{/pear/component/layui/layui.js}"></script>
<script th:src="@{/pear/component/pear/pear.js}"></script>
<script th:inline="javascript">
    let baseURL = /*[[@{/}]]*/ '';
    layui.use(['table', 'form', 'jquery', 'util'], function () {
        let table = layui.table;
        let form = layui.form;
        let $ = layui.jquery;
        let util = layui.util;


        let cols = [
            [
                {type: 'checkbox'},
                {field: 'formId', title: '表单key', minWidth: 100},
                {field: 'formName', title: '表单名称', minWidth: 100},
                {
                    field: 'formType', title: '表单类型', minWidth: 200, align: "center", templet: function (d) {
                        const map = {
                            0: "普通表单",
                            1: "调查问卷",
                            2: "工作流",
                        };
                        let typeText = map[d.formType] || "error";

                        return '<span>' + typeText + '</span>'
                    }
                },
                {field: 'createTime', title: '创建时间', minWidth: 200, align: "center"},
                {field: 'status', title: '启用', align: 'center', templet: '#form-enable'},
                {title: '操作', templet: '#form-bar', width: 400, align: 'center'}
            ]
        ]
        table.render({
            elem: '#form-table',
            url: baseURL + 'workflow/form/list',
            type: 'get',
            toolbar: '#form-toolbar',
            page: true,
            limit: 10,
            limits: [10, 20, 30],
            request: {
                pageName: 'pageNum',
                limitName: 'pageSize'
            },
            cols: cols,
            parseData: function (res) {
                return {
                    "code": res.code,
                    "msg": res.msg,
                    "count": res.data.total,
                    "data": res.data.list,
                };
            },
            response: {
                statusCode: 1000
            }
        });
        // 监听查询按钮，动态加载表格数据
        form.on('submit(form-query)', function (data) {
            // 获取表单中的查询条件
            let field = data.field;

            // 重新加载表格，并传递查询参数
            table.reload('form-table', {
                where: {
                    formName: field.formName,  // 栏目名查询条件
                },
                page: {
                    curr: 1 // 从第一页开始
                }
            });

            return false; // 阻止表单跳转
        });

        table.on('tool(form-table)', function (obj) {
            if (obj.event === 'remove') {
                window.remove(obj);
            } else if (obj.event === 'edit') {
                window.edit(obj);
            } else if (obj.event === 'survey') {
                window.survey(obj);
            } else if (obj.event === 'view') {
                window.view(obj);
            } else if (obj.event === 'share') {
                window.share(obj);
            }

        });

        table.on('toolbar(form-table)', function (obj) {
            if (obj.event === 'add') {
                window.add(obj);
            } else if (obj.event === 'batchRemove') {
                window.batchRemove(obj);
            }
        });

        form.on('switch(form-enable)', function (obj) {
            console.log(obj.value)
            let loading = layer.msg('修改中...', {
                icon: 16,
                shade: 0.01,
                time: 0
            });
            $.ajax({
                url: baseURL + 'workflow/form/enable/' + obj.value,
                type: 'post',
                success: function (result) {
                    layer.close(loading);
                    if (result.code === 1000) {
                        layer.msg(result.msg, {
                            icon: 1,
                            time: 2000
                        });
                    } else {
                        showErrorMessage(result.msg)
                    }
                },
                error: function () {
                    layer.close(loading);
                    layer.msg('服务器错误，请稍后再试！', {
                        icon: 2,
                        time: 2000
                    });
                }
            });
        });

        //打开新增页面
        window.add = function (obj) {
            layer.open({
                type: 2,
                title: '新增表单',
                shade: 0.1,
                area: ['100%', '100%'],
                content: 'form_add' // 更新为你的新增页面路径
            });
        };

        // 显示错误信息的函数
        function showErrorMessage(message) {
            layer.msg(message, {
                icon: 2,
                time: 2000
            });
        }

        //表单修改
        window.edit = function (obj) {
            let data = obj.data;
            $.ajax({
                url: baseURL + 'workflow/form/isFormFilled',
                data: {
                    formId: data.formId
                },
                type: 'get',
                success: function (result) {
                    if (result.data > 0) {
                        layer.msg('该表单已被填写，不能修改！', {
                            icon: 3,
                            time: 2000
                        });
                        return
                    }
                    window.fieldData = data.fieldData
                    window.formName = data.formName
                    window.formType = data.formType
                    window.formId = data.formId
                    layer.open({
                        type: 2,
                        title: '表单修改',
                        shade: 0.1,
                        shadeClose: true,
                        area: ['100%', '100%'],
                        content: 'form_edit',
                    })
                },
                error: function () {
                    layer.msg('服务器错误，请稍后再试！', {
                        icon: 2,
                        time: 2000
                    });
                }
            });

        }

        //删除表单
        window.remove = function (obj) {
            layer.confirm("删除该表单同时会删除表单的所有数据，建议先对表单数据进行备份。确定要删除该表单吗？", {
                icon: 3,
                title: '提示'
            }, function (index) {
                layer.close(index);
                let loading = layer.load();
                $.ajax({
                    url: baseURL + "workflow/form/delete/" + obj.data['formId'],
                    dataType: 'json',
                    type: 'post',
                    success: function (result) {
                        layer.close(loading);
                        if (result.code === 1000) {
                            layer.msg(result.msg, {
                                icon: 1,
                                time: 2000
                            }, function () {
                                table.reload('form-table');
                            });
                        } else {
                            showErrorMessage(result.msg)
                        }
                    },
                    error: function () {
                        layer.close(loading);
                        showErrorMessage('请求失败，请稍后再试');
                    }
                });
            });
        }
        window.share = function (obj) {
            let data = obj.data;
            if (data.formType !== 1) {
                layer.msg("只有类型为调查问卷的表单才可分享", {
                    icon: 3,
                    time: 2000
                });
                return;
            }
            const url = `${window.location.protocol}//${window.location.hostname}${window.location.port ? ':' + window.location.port : ''}`;
            let content = `${url}${baseURL}vm/form_submit?formId=${data.formId}&background=${encodeURIComponent(data.background)}`;

            // 复制链接到剪贴板
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(content).then(() => {
                    layer.msg("链接已复制到剪贴板", {
                        icon: 1,
                        time: 2000
                    });

                    // 延迟1.5秒后跳转到目标页面
                    setTimeout(() => {
                        window.open(content, '_blank');
                    }, 1500);
                }).catch(err => {
                    console.error('复制失败:', err);
                    layer.msg("复制失败，请手动复制链接", {
                        icon: 2,
                        time: 2000
                    });
                });
            } else {
                // 兼容旧浏览器
                let input = document.createElement('input');
                document.body.appendChild(input);
                input.value = content;
                input.select();
                if (document.execCommand('copy')) {
                    layer.msg("链接已复制到剪贴板", {
                        icon: 1,
                        time: 2000
                    });
                } else {
                    layer.msg("复制失败，请手动复制链接", {
                        icon: 2,
                        time: 2000
                    });
                }
                document.body.removeChild(input);

                // 延迟1.5秒后跳转到目标页面
                setTimeout(() => {
                    window.open(content, '_blank');
                }, 1500);
            }
        }
        //调查
        window.survey = function (obj) {
            let data = obj.data;
            window.fieldData = data.fieldData
            window.formName = data.formName
            window.formId = data.formId
            layer.open({
                type: 2,
                title: '表单调查',
                shade: 0.1,
                shadeClose: true,
                area: ['100%', '100%'],
                content: 'preview_submit',
                success: function (layero, index) {
                    // 数据回显
                    let body = layer.getChildFrame('body', index)
                    let data = obj.data
                    let imageUrl;
                    if (data.background && data.background.startsWith('upload')) {
                        imageUrl = baseURL + data.background; // 拼接 baseUrl
                    } else {
                        imageUrl = data.background; // 直接使用 data.background
                    }
                    body.find("#box1").css("background-image", `url('${imageUrl}')`);
                }
            })
        }
        //查看
        window.view = function (obj) {
            let data = obj.data;
            window.fieldData = data.fieldData
            window.formName = data.formName
            window.formId = data.formId
            layer.open({
                type: 2,
                title: '表单查看',
                shade: 0.1,
                shadeClose: true,
                area: ['100%', '100%'],
                content: 'form_data_management',
            })
        }


        //重置按钮
        document.getElementById('resetBtn').addEventListener('click', function () {
            table.reload('form-table', {
                page: {curr: 1}
            });
        });
    })
</script>
</body>
</html>
